package hamaster.jpbc.dao.impl;

import hamaster.jpbc.User;
import hamaster.jpbc.dao.UserDAO;
import hamaster.jpbc.sys.IBCSystem;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class UserDAOHibernateImpl extends CommonDAOHibernateImpl implements UserDAO {

	public UserDAOHibernateImpl() {
	}

	@Override
	public User login(String username, String password) {
		Session session = factory.openSession();
		String key = "username";
		if (username.matches("\\w+(\\.\\w+)*@\\w+(\\.\\w+)+"))
			key = "email";
		Criteria criteria = session.createCriteria(User.class).
			add(Restrictions.eq(key, username)).
			setFetchSize(1);
		List<?> result = criteria.list();
		if (result == null || result.size() < 1)
			return null;
		User user = (User) result.get(0);
		DateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String hash = IBCSystem.hash(password + df.format(user.getRegDate()));
		return hash.equalsIgnoreCase(user.getPassword()) ? user : null;
	}

	@Override
	public boolean isUsernameExist(String username) {
		return isColumnExist("username", username);
	}

	@Override
	public boolean isEmailExist(String email) {
		return isColumnExist("email", email);
	}

	private boolean isColumnExist(String name, String value) {
		Session session = factory.openSession();
		Criteria criteria = session.createCriteria(User.class).
				add(Restrictions.eq(name, value)).
				setFetchSize(1);
		List<?> result = criteria.list();
		boolean bool = result == null || result.size() < 1;
		session.close();
		return !bool;
	}
}
